//
//  UIImage+Ratio.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/19.
//

import UIKit

extension UIImage {
    func aspectRatioOfWH() -> CGFloat {
        var aspectRatio = 1.0
        if size.width > 0,
           size.height > 0 {
            aspectRatio = size.width / size.height
        }
        return aspectRatio
    }
    
    func isImageFullyTransparent() -> Bool {
        guard let cgImage = self.cgImage else { return false }
        
        let width = cgImage.width
        let height = cgImage.height
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bitsPerComponent = 8
        
        var pixelData = [UInt8](repeating: 0, count: width * height * bytesPerPixel)
        
        guard let context = CGContext(
            data: &pixelData,
            width: width,
            height: height,
            bitsPerComponent: bitsPerComponent,
            bytesPerRow: bytesPerRow,
            space: CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
        ) else { return false }
        
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        
        // 检查每个像素的 Alpha 值
        for i in stride(from: 3, to: pixelData.count, by: 4) {
            if pixelData[i] > 0 { // Alpha 值大于 0 表示不透明
                return false
            }
        }
        
        return true
    }
    
    func rotated(by angle: CGFloat) -> UIImage? {
        let radians = angle // 已经是弧度
        
        // 计算旋转后的新尺寸
        let rotatedRect = CGRect(origin: .zero, size: size)
            .applying(CGAffineTransform(rotationAngle: radians))
        let newSize = rotatedRect.size
        
        UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        
        // 移动到中心
        context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
        // 旋转
        context.rotate(by: radians)
        // 绘制图像（调整位置使其居中）
        draw(in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
        
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
